package org.example.leetcode.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.leetcode.common.exception.MyException;
import org.example.leetcode.common.pojo.PageResult;
import org.example.leetcode.core.domain.TQuestionType;
import org.example.leetcode.core.dao.TQuestionTypeMapper;
import org.example.leetcode.core.dto.QuestionTypeQueryCond;
import org.example.leetcode.core.service.TQuestionTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhc
 * @since 2024-02-25
 */
@Service
public class TQuestionTypeServiceImpl extends ServiceImpl<TQuestionTypeMapper, TQuestionType> implements TQuestionTypeService {

    @Override
    public List<TQuestionType> all() {
        return this.getBaseMapper().selectList(null);
    }

    @Override
    public void add(TQuestionType tQuestionType) {
        if(!StringUtils.hasText(tQuestionType.getName())||!StringUtils.hasText(tQuestionType.getCode())){
            throw new MyException("请完善类型信息");
        }
        Integer a = this.baseMapper.selectCount(new LambdaQueryWrapper<TQuestionType>()
                .eq(TQuestionType::getCode, tQuestionType.getCode()));
        Integer b = this.baseMapper.selectCount(new LambdaQueryWrapper<TQuestionType>()
                .eq(TQuestionType::getName, tQuestionType.getName()));
        if(tQuestionType.getId()==null&&(a|b)>0){
            throw new MyException("类型重复");
        }
        this.saveOrUpdate(tQuestionType);
    }

    @Override
    public void delete(String code) {
        TQuestionType tQuestionType = this.baseMapper.selectOne(new LambdaQueryWrapper<TQuestionType>()
                .eq(TQuestionType::getCode,code ));
        if(tQuestionType==null){
            throw new MyException("数据不存在");
        }
        this.getBaseMapper().deleteById(tQuestionType.getIsDeleted());
    }

    @Override
    public PageResult<TQuestionType> page(QuestionTypeQueryCond questionTypeQueryCond) {
        Page<TQuestionType> tQuestionTypePage = new Page<>(questionTypeQueryCond.getPageNo(),questionTypeQueryCond.getPageSize());
        Page<TQuestionType> res = this.getBaseMapper().selectPage(tQuestionTypePage, null);
        PageResult<TQuestionType> tQuestionTypePageResult = new PageResult<>();
        BeanUtils.copyProperties(res,tQuestionTypePageResult);
        return tQuestionTypePageResult;
    }
}
